import editForm from "../form/index.vue";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection } from "@pureadmin/utils";
import { getPage, add, update, del, setStatus } from "@/api/base";
import { usePublicHooks } from "../../../hooks";
import { ElMessageBox } from "element-plus";
import { h, ref, toRaw, reactive, onMounted } from "vue";

export function useDevice() {
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const switchLoadMap = ref({});
  const { switchStyle } = usePublicHooks();

  const typeOption = [
    { type: "primary", effect: "dark", value: 0, label: "智能仓" },
    { type: "info", effect: "dark", value: 1, label: "7寸固定料架" },
    { type: "success", effect: "dark", value: 2, label: "13寸固定料架" },
    { type: "warning", effect: "dark", value: 3, label: "固定货架" },
    { type: "danger", effect: "dark", value: 4, label: "防潮箱" },
    { type: "primary", effect: "light", value: 5, label: "首套料车" },
    { type: "info", effect: "light", value: 6, label: "续料车" },
    { type: "success", effect: "light", value: 7, label: "移动货架" },
    { type: "warning", effect: "light", value: 8, label: "移动料箱" }
  ];

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const form = reactive({
    name: "",
    code: "",
    pageIndex: pagination.currentPage,
    pageSize: pagination.pageSize
  });

  const columns: TableColumnList = [
    {
      label: "序号",
      width: 60,
      type: "index"
    },
    {
      label: "名称",
      prop: "Name"
    },
    {
      label: "编码",
      prop: "Code"
    },
    {
      label: "设备类型",
      prop: "Type",
      cellRenderer: ({ row, props }) => {
        const model = typeOption.find(p => p.value == row.Type);
        if (!model) return null;
        return (
          <el-tag size={props.size} type={model.type} effect={model.effect}>
            {model.label}
          </el-tag>
        );
      }
    },
    {
      label: "库存数量",
      prop: "Qty"
    },
    {
      label: "状态",
      prop: "Status",
      minWidth: 90,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.Status}
          active-value={1}
          inactive-value={0}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.Status === 0 ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.Name
      }</strong>设备吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        let result = await setStatus("device", {
          id: row.Id,
          status: row.Status
        });
        if (!result.success) {
          message(result.Message, { type: "error" });
          onSearch();
          return;
        }
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        setTimeout(() => {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          message("已成功修改用户状态", {
            type: "success"
          });
        }, 300);
      })
      .catch(() => {
        row.Status === 0 ? (row.Status = 1) : (row.Status = 0);
      });
  }

  async function handleDelete(row) {
    let result = await del("device", { id: row.Id });
    if (result.success) {
      message(`您删除了编码为${row.Code}的这条数据`, { type: "success" });
      onSearch();
    } else {
      message(result.Message, { type: "error" });
    }
  }

  async function onSearch() {
    loading.value = true;
    const { Data } = await getPage("device", toRaw(form));
    dataList.value = Data.data;
    pagination.total = Data.total;
    pagination.pageSize = Data.pageSize;
    pagination.currentPage = Data.pageIndex;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?) {
    addDialog({
      title: `${title}设备`,
      props: {
        formInline: {
          Title: title,
          Id: row?.Id ?? 0,
          Name: row?.Name ?? "",
          Code: row?.Code ?? "",
          Type: row?.Type ?? 0,
          Qty: row?.Qty ?? 0,
          Status: row?.Status ?? 1
        }
      },
      width: "46%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline;
        function chores() {
          message(`您${title}了编码为${curData.Code}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            let result;
            // 表单规则校验通过
            if (title === "新增") {
              result = await add("device", curData);
            } else {
              result = await update("device", curData);
            }
            if (result.success) {
              chores();
            } else {
              message(result.Message, { type: "error" });
            }
          }
        });
      }
    });
  }

  function handleCurrentChange(val: number) {
    form.pageIndex = val;
    onSearch();
  }

  function handleSizeChange(val: number) {
    form.pageSize = val;
    onSearch();
  }

  onMounted(async () => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    typeOption,
    deviceDetection,
    onSearch,
    resetForm,
    openDialog,
    handleDelete,
    handleCurrentChange,
    handleSizeChange
  };
}
